package com.zdemo.pressure;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger;

import com.zdemo.common.Logging;

public class RequestThreadPoolExecutor extends ThreadPoolExecutor {

	public RequestThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
			long keepAliveTime, TimeUnit unit,
			BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,
			RejectedExecutionHandler handler) {

		super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
				threadFactory, handler);
	}

	private final ThreadLocal<Long> startTime = new ThreadLocal<Long>();
	private final AtomicLong numTasks = new AtomicLong();
	private final AtomicLong totalTime = new AtomicLong();
	private static final Logger log = Logging.getLogger();

	@Override
	protected void beforeExecute(Thread t, Runnable r) {
		super.beforeExecute(t, r);
		log.info(String.format("Thread %s: start %s", t, r));
		startTime.set(System.currentTimeMillis());
	}

	@Override
	protected void afterExecute(Runnable r, Throwable t) {
		super.afterExecute(r, t);
		long endTime = System.currentTimeMillis();
		long taskTime = endTime - startTime.get();
		numTasks.incrementAndGet();
		totalTime.addAndGet(taskTime);
		log.info(String
				.format("Thread %s: start %s, time=%dms", t, r, taskTime));
	}

	@Override
	protected void terminated() {
		try {
			log.info(String.format("Terminated avg time = %dms",
					totalTime.get() / numTasks.get()));
		} finally {
			super.terminated();
		}
	}

}
